#!/bin/bash

. /etc/parallelcluster/cfnconfig

# Error exit function
function error_exit () {
  script=`basename $0`
  echo "parallelcluster: $script - $1"
  logger -t parallelcluster "$script - $1"
  exit 1
}

function download_run (){
    url=$1
    scheme=$(echo "${url}"| cut -d: -f1)
    tmpfile=$(mktemp)
    trap "/bin/rm $tmpfile" RETURN
    if [ "${scheme}" == "s3" ]; then
      <%= node['cfncluster']['cookbook_virtualenv_path'] %>/bin/aws --region ${cfn_region} s3 cp ${url} - > $tmpfile || return 1
    else
      wget -qO- ${url} > $tmpfile || return 1
    fi
    chmod +x $tmpfile || return 1
    $tmpfile $@ || error_exit "Failed to run boot_as_master $ACTION, $file failed with non 0 return code: $?"
}

function run_preinstall () {
  if [ "${cfn_preinstall}" != "NONE" ]; then
    file="${cfn_preinstall}"
    if [ "${cfn_preinstall_args}" != "NONE" ]; then
        download_run ${cfn_preinstall} ${cfn_preinstall_args}
    else
        download_run ${cfn_preinstall}
    fi
  fi || error_exit "Failed to run boot_as_master preinstall"
}

function run_postinstall () {
  RC=0
  if [ "${cfn_postinstall}" != "NONE" ]; then
    file="${cfn_postinstall}"
    if [ "${cfn_postinstall_args}" != "NONE" ]; then
        download_run ${cfn_postinstall} ${cfn_postinstall_args}
    else
        download_run ${cfn_postinstall}
    fi
  fi || error_exit "Failed to run boot_as_master postinstall"
}

ACTION=${1#?}

case $ACTION in
  preinstall)
    run_preinstall
    ;;

  postinstall)
    run_postinstall
    ;;

  *)
    echo "Unknown action. Exit gracefully"
    exit 0

esac
